/**
 * @author marylin
 */


function VatataPublicClass(){
	
	var delayTimer = null;
	//单标签文字滚动
	var RollObj = new Object();
	var m_roll_timer = null;
	var m_defaultText = "";
	//MAX TEXT ,over it to start roll
	const MAX_TEXT_LENGTH=6;
	//0.5 sec roll speed
	const ROLL_SPEED = 0.5;
	//2 sec start roll
	const ROLL_START_TIME = 2;
	function startOther(ele) {
		var _text = ele.textContent.split("");
		_text.push(" ");
		
		if(!_text||_text.length<=MAX_TEXT_LENGTH)	
			return;
			
		var _id = ele;
		
		if(m_roll_timer)
			clearInterval(m_roll_timer);
		
		m_roll_timer = setInterval(function () {
			_text.push(_text.shift()); //将字符串数组第一个字符剪切并添加到数组末尾
			_id.textContent = _text.join("");
		}, ROLL_SPEED*1000);
	}
	function startInput(ele) {
		var _text = ele.value.split("");
		_text.push(" ");
		
		if(!_text||_text.length<=MAX_TEXT_LENGTH)	
			return;
			
		var _id = ele;
		
		if(m_roll_timer)
			clearInterval(m_roll_timer);
		
		m_roll_timer = setInterval(function () {
			_text.push(_text.shift()); //将字符串数组第一个字符剪切并添加到数组末尾
			//类似挤牙膏^!^
			_id.value = _text.join("");
		}, ROLL_SPEED*1000);
	}
	function stopRoll(ele) {
		if(m_roll_timer)
			clearInterval(m_roll_timer);
		
		if(ele.tagName.toLowerCase()=="input")
			ele.value = m_defaultText;
		else
			ele.innerHTML = m_defaultText;
	}
	this.startRoll = function(ele){
		if(delayTimer)
			clearTimeout(delayTimer)
		
		//设置默认Text
		if(ele.tagName.toLowerCase()=="input")
			m_defaultText = ele.value;
		else
			m_defaultText = ele.innerHTML;
		
		delayTimer = setTimeout(function(){
			if(ele.tagName.toLowerCase()=="input")
				startInput(ele)
			else
				startOther(ele)
		},ROLL_START_TIME*1000);
	}
	this.stopRoll = function(ele){
		if(delayTimer)
			clearTimeout(delayTimer)
			
		stopRoll(ele);
	}
	//得到location.href参数.
	this.getQueryString = function(name){
		if(location.href.indexOf("?")==-1 || location.href.indexOf(name+'=')==-1)
		{
			return '';
		}
		var queryString = location.href.substring(location.href.indexOf("?")+1);
		var parameters = queryString.split("&");
		var pos, paraName, paraValue;
		for(var i=0; i<parameters.length; i++)
		{
			pos = parameters[i].indexOf('=');
			if(pos == -1) { continue; }
			 
			paraName = parameters[i].substring(0, pos);
			paraValue = parameters[i].substring(pos + 1);
			 
			if(paraName == name)
			{
				var value = unescape(paraValue.replace(/\+/g, " "));
				value = value.replace(/#/,"");
				return value;
			}
		}
		return '';
	}
	
	//创造android提供的相应对象.不过这个依靠window.onWAEReady.须在此函数里才能创建.
	this.createAndroidPlug = function(type){return createAndroidPlug(type)}
	function createAndroidPlug(type){
		var _obj = null;
		switch(type){
			case "Application":{
				//应用程序对象
				if(wae.can("Application")||wae.can("Application")=="true")
					_obj = wae.create("Application");
			}
			break;
			case "Http":{
				//网络对象
				if(wae.can("Net.HttpClient")||wae.can("Net.HttpClient")=="true")
					_obj = wae.create("Net.HttpClient");
			}
			break;
			case "License":{
				//License对象
				if(wae.can("license.License")||wae.can("license.License")=="true")
					_obj = wae.create("license.License");
			}
			break;
			case "Menu":{
				//系统菜单对象
				if(wae.can("UI.SysMenu")||wae.can("UI.SysMenu")=="true")
					_obj = wae.create("UI.SysMenu");
			}
			break;
			case "Player":{
				//播放器对象
				if(wae.can("Media.StandalonePlayer")||wae.can("Media.StandalonePlayer")=="true")
					_obj = wae.create("Media.StandalonePlayer");
			}
			break;
			case "Liveepg":{
				//直播插件对象
				if(wae.can("Location")||wae.can("Location")=="true")
					_obj = wae.create("plugins.LiveEPGJsExpands");	
			}
			break;
			case "Location":{
				if(wae.can("Location")||wae.can("Location")=="true")
					_obj = wae.create("Location");	
			}
			break;
			case "Internationalization":{
				//国际化对象
				if(wae.can("Internationalization")||wae.can("Internationalization")=="true")
					_obj = wae.create("Internationalization");
			}
			break;
			case "Intent":{
				//Intent
				if(wae.can("Intent")||wae.can("Intent")=="true")
					_obj = wae.create("Intent");	
			}
			break;
			case "Manager":{
				//Market.Manager
				if(wae.can("Market.Manager")||wae.can("Market.Manager")=="true")
					_obj = wae.create("Market.Manager");
			}
			break;
			case "EventSender":{
				if(wae.can("EventSender")||wae.can("EventSender")=="true")
					_obj = wae.create("EventSender");
			}
			break;
			case "MarketDatabase":{
				if(wae.can("Market.OutsideInquirier")||wae.can("Market.OutsideInquirier")=="true")
					_obj = wae.create("Market.OutsideInquirier");
			}break;
			case "Toast":{
				if(wae.can("Toast")||wae.can("Toast")=="true")
					_obj = wae.create("Toast");
			}break;
			case "EventTransition":{
				if(wae.can("EventTransition")||wae.can("EventTransition")=="true")
					_obj = wae.create("EventTransition");
			}break;
			case "SinaWeibo":{
				if(wae.can("UI.SinaMicroBlogLogin")||wae.can("UI.SinaMicroBlogLogin")=="true")
					_obj = wae.create("UI.SinaMicroBlogLogin");
			}break;
			case "NetTvShare":{
				if(wae.can("Net.ShareSender")||wae.can("Net.ShareSender")=="true")
					_obj = wae.create("Net.ShareSender");
			}
			break;
			case "StandPlayer":{
				if(wae.can("Media.StandalonePlayer")||wae.can("Media.StandalonePlayer")=="true")
					_obj = wae.create("Media.StandalonePlayer");
			}
			break;
			case "UIDialog":{
				if(wae.can("UI.Dialog")||wae.can("UI.Dialog")=="true")
					_obj = wae.create("UI.Dialog");
			}
			break;
			case "ErrorHandler":{
				if(wae.can("tools.ErrorHandler")||wae.can("tools.ErrorHandler")=="true")
					_obj = wae.create("tools.ErrorHandler");
			}
			break;
			case "PageHandler":{
				if(wae.can("PageHandler")||wae.can("PageHandler")=="true")
					_obj = wae.create("PageHandler");
			}break;
			case "EventListener":{
				if(wae.can("EventListener")||wae.can("EventListener")=="true")
					_obj = wae.create("EventListener");
			}
			break;
			case "Device":{
				if(wae.can("Devices")||wae.can("Devices")=="true")
					_obj = wae.create("Devices");
			}break;
			case "NeworkManager":{
				if(wae.can("Net.NetworkManager")||wae.can("Net.NetworkManager")=="true")
					_obj = wae._create("Net.NetworkManager");
			}
			break;
		}
		return _obj;
	}
	this.getJsonObjByString = function(str){
		if(!str)
			return null;
			
		return eval("("+str+")");
	}
	this.getJsonObjByUrl = function(url){
		if(!m_http)
			var m_http = this.createAndroidPlug("Http");
		//设置是否采用获取数据返回cache数据,后台刷新数据的模式
		m_http.setReturnCacheData(true);
		//获取url内容
		m_http.setReadTimeOut(15);		
		var _content = m_http.getWithSync(url, 15);
		if (!_content)
			return null;
			
		return eval("("+_content+")");
	}
	
	this.getJsonStrByUrl = function(url){
		if(!m_http)
			var m_http = this.createAndroidPlug("Http");
		//设置是否采用获取数据返回cache数据,后台刷新数据的模式
		m_http.setReturnCacheData(true);
		//获取url内容
		m_http.setReadTimeOut(15);		
		var _content = m_http.getWithSync(url, 15);
		if (!_content)
			return null;
			
		return _content;
	}
	var m_old_date = "";
	var m_old_time = "";
	var m_updateTimeTimer = null;
	//时间机制
	this.updateTime = function(dateId,timeId,weatherId,weatherImgId){
	// function updateTime(dateId,timeId,weatherId,weatherImgId){
		if(m_updateTimeTimer)
			clearInterval(m_updateTimeTimer)
		try{
		var _day_symbol = "AM";
		var _date_obj = new Date();
		var _year = _date_obj.getFullYear();
		var _month = _date_obj.getMonth()+1;
		var _day = _date_obj.getDate();
		var _date = _year+"-"+_month+"-"+_day;
		
		var _hour = _date_obj.getHours();
		if(_hour>=0&&_hour<10)
			_hour = "0"+_hour;
		var _min = _date_obj.getMinutes();
		if(_min>=0&&_min<10)
			_min = "0"+_min;
		var _sec = _date_obj.getSeconds();
		if(_sec>=0&&_sec<10)
			_sec = "0"+_sec;
			
		var _time = _hour+":"+_min;
		
		var _week_day = _date_obj.getDay();
		var _week_json = {0:"星期日",1:"星期一",2:"星期二",3:"星期三",4:"星期四",5:"星期五",6:"星期六"};
		var _week = _week_json[_week_day];
		
		if(_hour>12)
			_day_symbol = "PM";
			
		if(_week)
			dateId.textContent = _week;
		
		if(m_old_date!=_date||m_old_time!=_time){
			timeId.textContent =_date+"  "+_day_symbol+" "+ _time;
		}
		
		//记录上一次的时间
		m_old_date = _date;
		m_old_time = _time;
		
		//每5秒一对时.
		updateTemp(dateId,timeId,weatherId,weatherImgId);
		m_updateTimeTimer = setTimeout(function(){VatataPublic.updateTime(dateId,timeId,weatherId,weatherImgId)},60000);
		}catch(e){return;}
	}
	//天气
 	function getTemperature(dateId,timeId,weatherId,weatherImgId){
		
		var weather = window.localStorage.getItem('WEATHER');
	    if (weather) {
			var str_degrees = window.localStorage.getItem('DEGRESS');
			weatherId.innerHTML=weather;
			//weatherImgId.scr = str_degrees;
			if(str_degrees){
				var wImg = new Image();
				wImg.src = str_degrees;
				wImg.onload = function (){
					weatherImgId.src = this.src;
					weatherImgId.style.visibility = "visible";
					timeId.style.display = "block";
					dateId.style.display = "block";
					weatherId.style.display = "block";
					weatherImgId.style.display = "block";

				}
				
				wImg.onerror = function (){
					setTimeout(function(){
						VatataPublic.updatetime_Temperature(dateId,timeId,weatherId,weatherImgId);
					},60000)
				}
			}
			
	    }else{
	    	var now_date = ''
	    	try{
				var city_obj = createAndroidPlug("Http");
				var net_obj = createAndroidPlug("Http");
	    	}catch(e){return;}
	    	
		    var city_address = 'http://ip.cms.sohu.com/ip.do?type=json';
		    
	        city_obj.getWithAsync(city_address, 30);
	        city_obj.oncomplete = function(e){
	            var argument0 = e.arguments[0].toLocaleString(); //URL
	            var argument1 = e.arguments[1].toLocaleString(); //Response Code
	            var argument2 = e.arguments[2].toLocaleString(); //content
	            var content = argument2;
	            
				if(content){
					var address = content.match(/cid\:[\S\s]*?\,/)[0].replace(/cid\:|\,/g, '');
					
					var Response = city_obj.getResponseHeaders(argument0);
					if(Response){
						var data =Response.match(/"Date":"[\S\s]*?"/)[0].replace(/"Date":"|"/g,'').split(",")[1].split(" ");
						day = data[1];
						month = data[2];
						switch (month){
						  case 'Jan':
						   month="01";
						   break;
						  case 'Feb':
						   month="02";
						   break;
						  case 'Mar':
						   month="03";
						   break;
						  case 'Apr':
						   month="04";
						   break;
						  case 'May':
						   month="05";
						   break;
						  case 'Jun':
						   month="06";
						   break;
						  case 'Jul':
						   month="07";
						   break;
						  case 'Aug':
						   month="08";
						   break;
						  case 'Sep':
						   month="09";
						   break;
						  case 'Oct':
						   month="10";
						   break;
						  case 'Nov':
						   month="11";
						   break;
						  case 'Dec':
						   month="12";
						   break;
						 }
						year = data[3]
						now_date = year+month+day;
						
						var degrees = "http://m.sohu.com/weather/cms/"+ now_date + "/" + address + ".3days.json";
						window.localStorage.setItem('YEAR',year);
						window.localStorage.setItem('MONTH',month);
						window.localStorage.setItem('DAY',day);
						
						net_obj.getWithAsync(degrees, 30);
					}
				}
			}
			net_obj.oncomplete = function(e){
				var argument0 = e.arguments[0].toLocaleString(); //URL
				var argument1 = e.arguments[1].toLocaleString(); //Response Code
				var argument2 = e.arguments[2].toLocaleString(); //content
				var content = argument2;
				if(content){
					var weather_low = content.match(/\"Temperature\"\:\{\"Low\"\:\"[\S\s]*?\}\,\"/)[0].match(/\"Low\"\:\"[\S\s]*?\"\,/)[0].replace(/\"Low\"\:\"|\"\,/g, '');
					var weather_high = content.match(/\"Temperature\"\:\{\"Low\"\:\"[\S\s]*?\}\,\"/)[0].match(/\"High\"\:\"[\S\s]*?\"\}\,/)[0].replace(/\"High\"\:\"|\"\}\,/g, '');
					var weather = "今日气温:"+weather_low + '/' + weather_high + "℃";
					var weather_img = content.match(/\"Weather\"\:\{\"Desc\"[\S\s]*?\"\}\,/)[0].match(/\"Symbol\"\:\"[\S\s]*?\"\}\,/)[0].replace(/\"Symbol\"\:\"|\"\}\,/g, '');
					var weather_logo = "http://news.sohu.com/upload/weather1217/wp" + weather_img[0] + weather_img[1] + ".gif";
					weatherId.textContent = weather;
					if(weather_logo){
						
						var wImg = new Image();
						wImg.src = weather_logo;
						wImg.onload = function (){
							weatherImgId.src = this.src;
							weatherImgId.style.visibility = "visible";
							window.localStorage.setItem('WEATHER',weather);
							window.localStorage.setItem('DEGRESS',weather_logo);
							timeId.style.display = "block";
							dateId.style.display = "block";
							weatherId.style.display = "block";
							weatherImgId.style.display = "block";
						}
						
						wImg.onerror = function (){
							setTimeout(function(){
								VatataPublic.updatetime_Temperature(dateId,timeId,weatherId,weatherImgId);
							},60000)
						}
					}
					
				}
			}
	    }
	}
	this.updatetime_Temperature = function(dateId,timeId,weatherId,weatherImgId){
		this.updateTime(dateId,timeId,weatherId,weatherImgId);
		getTemperature(dateId,timeId,weatherId,weatherImgId);
	}

	function updateTemp(dateId,timeId,weatherId,weatherImgId){
		var _date_obj = new Date();
		year = window.localStorage.getItem('YEAR');
		month = window.localStorage.getItem('MONTH');
		day = window.localStorage.getItem('DAY');
		var _year = _date_obj.getFullYear();
		var _month = _date_obj.getMonth()+1;
		var _day = _date_obj.getDate();
		if(_year>year||_month>month||_day>day){
			window.localStorage.removeItem('WEATHER');
			window.localStorage.removeItem('DEGRESS');
			getTemperature(dateId,timeId,weatherId,weatherImgId);
		}
	}
	this.writeText = function(id,str){
		if(!str)
			return;
		id.textContent = str;
	}
	this.writeValue = function(id,value){
		if(!value)
			return;
		id.value = value;
	}
	this.writeHtml = function(id,str){
		id.innerHTML = str;
	}
	function getErrorCode(msg){
		var _isshow = false;
		if(!msg)
			return ["0",_isshow];
		/*
		 * {"xxx":{"errorcode":"00000","isshow":false}}
		 */
		if(!window.g_tipsJson){
			return ["0",_isshow];
		}
		var _errorCodeJson = g_tipsJson[msg];
		if(!_errorCodeJson){
			return ["0",_isshow];
		}
		var _errorcode = _errorCodeJson.errorcode;
		if(!_errorcode)
			return ["0",_isshow];
		
		if(_errorCodeJson.isshow)
			_isshow = _errorCodeJson.isshow;
			
		return [_errorcode,_isshow];
	}
	this.openMessage = function(msg){

		var _callbackFun = null;
		if(arguments.length>1&&arguments[1])
			_callbackFun = arguments[1];
		
		//得到error对应的数组
		//0为errorcode ，1为是否显示错误代码
		var _errorCodeArr = getErrorCode(msg);
		var _errorCode = _errorCodeArr[0];
		var _isErrorShow = _errorCodeArr[1];
		//有些errorcode不需要显示。所以这里直接return
		if(!_isErrorShow||_isErrorShow=="false")
			return;
			
		//如果有回调函数则需要传入回调函数给tips
		if(_callbackFun){
			VatataTips.showMessageByErrorCode(_errorCode,_callbackFun);
			return;
		}
		VatataTips.showMessageByErrorCode(_errorCode);
		// alert(msg);
		
	}
}
var VatataPublic = new VatataPublicClass();
